<?php


namespace app\index\controller;

use app\index\model\ActionRole;
use app\index\model\Group;
use app\index\model\Menu;
use app\index\model\News;
use app\index\model\OrderPayment;
use app\index\model\Role;
use app\index\model\Todo;
use app\index\model\User;
use think\Env;
use think\Exception;
use think\response\Json;

class UserController extends BaseController
{

    public function getDayText(): Json
    {
        
        $dir=Env::get('resource.path','/var/www/html/images/').'static'.DS.'dayText.json';
        $mouth=date('m');
        $day=date('d');
        $string='';
        if(is_file($dir)){
            //存在已只读方式打开
            $files=fopen($dir, 'rb');
            $file_size=filesize($dir);
            //判断文件是否有内容
            if($file_size>0) {
                $json = fread($files, filesize($dir));
                $data = json_decode($json, true);
                $string=$data[$mouth][$day]??'';
            }
        }
        if($string){
            return json(['code'=>0,'dayText'=>$string['text'],'dayTextSource'=>$string['source']]);
        }
        $string='欲买桂花同载酒，终不似，少年游。';
        return json(['code'=>0,'dayText'=>$string,'dayTextSource'=>'唐多令·芦叶满汀洲']);
    }

    /**
     * getUserParam
     * 获取用户数组详情
     * @url /user/param
     * @method POST
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author Asira
     * @date 2021/1/25
     */
    public function getUserParam(): Json
    {
        $role_list=Role::getRoleCascadeList();
        $group_list=Group::getGroupList();
        $menu_list=Menu::getMenuList();
        return json(['code'=>0,'role_list'=>$role_list,'group_list'=>$group_list,'menu_list'=>$menu_list]);
    }

    /**
     * getUserList
     * 获取用户列表
     * @url /user/list
     * @method POST
     * @return Json
     * @author Asira
     * @date 2021/2/3
     */
    public function getUserList(): Json
    {
        $page=input('post.pageIndex',1);
        $size=input('post.pageSize',10);
        $post=input('post.',[],'trim');
        $search_param=[
            'search_key'=>$post['search_key']??null,
            'search_value'=>$post['search_value']??null,
            'id'=>$post['user']??null,
            'group_id'=>$post['group_id']??null,
            'role_id'=>$post['role_id']??null,
        ];
        $page_param=[
            'page_num'=>$page,
            'page_size'=>$size,
        ];
        ['status'=>$status,'result'=>$result]=User::getUserRoleList($search_param,$page_param);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'data'=>$result['data'],'total'=>$result['total']]);
    }

    /**
     * createUser
     * 创建用户
     * @url /user/create
     * @method POST
     * @return Json
     * @author Asira
     * @date 2021/2/3
     */
    public function createUser(): Json
    {
        $data=input('post.');
        if(!$data['user_name']){
            return json(['code'=>1,'msg'=>'用户名不能为空']);
        }
        if(!$data['password']){
            return json(['code'=>1,'msg'=>'密码不能为空']);
        }
        $data=[
            'user_name'=>$data['user_name'],
            'password'=>md5($data['password']),
            'role'=>$data['role_id'][0]??null,
            'role_detail_id'=>$data['role_id'][1]??null,
            'group_id'=>$data['group_id'],
        ];
        ['status'=>$status,'result'=>$result]=User::createUser($data);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

    /**
     * getUserById
     * 根据id获取用户数据
     * @url /user/get/id
     * @method
     * @return Json
     * @author Asira
     * @date 2021/2/3
     */
    public function getUserById(): Json
    {
        $id=input('post.id');
        $user_data=User::getUserById($id);
        if(empty($user_data)){
            return json(['code'=>1,'msg'=>'未找到数据']);
        }
        $user_data['role_id']=[];
        if($user_data['role']) {
            $user_data['role_id'][] = $user_data['role'];
            if($user_data['role_detail_id']){
                $user_data['role_id'][]=$user_data['role_detail_id'];
            }
        }

        return json(['code'=>0,'data'=>$user_data]);
    }

    /**
     * updateUser
     * 更新用户
     * @url /user/update
     * @method POST
     * @return Json
     * @author Asira
     * @date 2021/2/3
     */
    public function updateUser(): Json
    {
        $data=input('post.');
        if(!$data['user_name']){
            return json(['code'=>1,'msg'=>'用户名不能为空']);
        }
        $data=[
            'id'=>$data['id'],
            'user_name'=>$data['user_name'],
            'role'=>$data['role_id'][0]??null,
            'role_detail_id'=>$data['role_id'][1]??null,
            'group_id'=>$data['group_id'],
        ];
        ['status'=>$status,'result'=>$result]=User::updateUser($data);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

    /**
     * getTodoList
     * 获取todolist 同组互相查看
     * @url /home/todo/list
     * @method POST
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author Asira
     * @date 2021/2/8
     */
    public function getTodoList(): Json
    {
        $group=$this->user_session['group_id'];

        $group_list=Group::getGroupList();

        ['action_role'=>$action_role]=ActionRole::checkUserActionRole('todo_list');
        $action_role=$action_role['todo_list'];
        if($action_role===0){
            return json(['code'=>0,'data'=>[],'group_list'=>[],'action_role'=>$action_role]);
        }

        $data=Todo::getTodoList($group);
        if(!empty($data)){
            foreach ($data as $key=>$value){
                $data[$key]['status']= $value['status'] !== 0;
                $data[$key]['is_new']=false;
                $data[$key]['edit']=false;
            }
        }
        return json(['code'=>0,'data'=>$data,'group_list'=>$group_list,'action_role'=>$action_role]);
    }

    public function saveTodoList(): Json
    {
        $id=input('post.id');
        $title=input('post.title');
        $text=input('post.text');
        $customer=input('post.customer');
        $order_id=input('post.order_id');
        $group=input('post.group');
        $ws_id=input('post.ws_id');

        $todo=new Todo();
        if($id){
            $todo_data=$todo::get($id);
            if($todo_data === null){
                return json(['code'=>1,'msg'=>'未找到todo']);
            }
            $todo_data->title=$title;
            $todo_data->text=$text;
            $todo_data->customer=$customer;
            $todo_data->order_id=$order_id;
            $todo_data->create_group=$group;
            $result_row=$todo_data->save();
            $message='有一条todo已更新';
            $type='update';
        }else{
            $todo->title=$title;
            $todo->text=$text;
            $todo->customer=$customer;
            $todo->order_id=$order_id;
            $todo->status=0;
            $todo->create_user=$this->user_session['id'];
            $todo->create_group=$group;
            $result_row=$todo->save();
            $id=$todo->id;
            $message='有一条新的todo';
            $type='push';
        }
        $data=$todo::getTodoById($id);
        try {
            if ($result_row) {
                $user = User::where('status', 1)
                    ->where('del_flag', 0)
                    ->where(function ($query)use($group){
                        $query->where('role',1)->whereOr('group_id',$group);
                    })
//                    ->where('id','<>',$this->user_session['id'])
                    ->column('id');
                if($user) {
                    $this->sendWSMessage($user,$ws_id, ['type' => $type, 'key' => 'todo_list', 'msg' => $message, 'data' => $data]);
                }
            }
        }catch (Exception $e){
            trace('todolist send error '.$e->getMessage(),'error');
        }
        return json(['code'=>0,'data'=>$data]);
    }

    public function completeTodoList(): Json
    {
        $text=input('post.text');
        $id=input('post.id');
        $ws_id=input('post.ws_id');

        $todo=new Todo();
        $todo_data=$todo::get($id);
        if($todo_data === null){
            return json(['code'=>1,'msg'=>'未找到todo']);
        }
        $todo_data->complete_text=$text;
        $todo_data->complete_user=$this->user_session['id'];
        $todo_data->status=1;
        $result_row=$todo_data->save();
        $message='有一条todo已完成';
        $type='update';

        $data=$todo::getTodoById($id);
        try {
            if ($result_row) {
                $user = User::where('status', 1)
                    ->where('del_flag', 0)
                    ->where(function ($query)use($data){
                        $query->where('role',1)->whereOr('group_id',$data['group']);
                    })
//                    ->where('id','<>',$this->user_session['id'])
                    ->column('id');
                if($user) {
                    $this->sendWSMessage($user,$ws_id, ['type' => $type, 'key' => 'todo_list', 'msg' => $message, 'data' => $data]);
                }
            }
        }catch (Exception $e){
            trace('todolist complete error '.$e->getMessage(),'error');
        }
        return json(['code'=>0,'msg'=>'已更新']);
    }

    public function getPaymentList(){
        ['action_role'=>$action_role,'group'=>$search_group,'search_user'=>$search_user]=ActionRole::checkUserActionRole('order');

        if($action_role===0){
            return json(['code'=>0,'data'=>[]]);
        }
        $order=OrderPayment::getHomePaymentList($search_group,$search_user);

        return json(['code'=>0,'data'=>$order]);
    }

    public function getNewsList(){
        ['action_role'=>$action_role,'group'=>$search_group,'search_user'=>$search_user]=ActionRole::checkUserActionRole('waybill_news_list');

        if($action_role['waybill_news_list']===0){
            return json(['code'=>0,'data'=>[]]);
        }
        $data=News::getNewsList($search_group,2);

        return json(['code'=>0,'data'=>$data]);
    }

    public function getSalesAmount(){
        $CustomerOrder=new \app\websocket\model\CustomerOrder();
        $data=$CustomerOrder::getCustomerSalesPolyline($this->user_session['id']);
        if($data!==false){
            return json(['code'=>0,'data'=>$data]);
        }
        return json(['code'=>1,'msg'=>'获取失败']);
    }
}